<template>
    <form class="validate-from-container mb-4">
        <slot></slot>
        <div class="submit-area" @click.prevent="submitForm">
            <slot name="submit">
                <button type="submit" class="btn btn-primary me-3">submit</button>
                <button type="reset"  class="btn btn-success">reset</button>
            </slot>
        </div>
    </form>
</template>

<script setup lang="ts">
import emitter, { ValidateFunc } from '../hooks/useEmitter'
import { onUnmounted } from 'vue'

let funcArr: ValidateFunc[] = []
const emit = defineEmits(['from-submit'])
const submitForm = () => {
    const result = funcArr.map(func => func()).every(val => val)
    emit('from-submit', result)
}

const callback = (func: ValidateFunc) => {
    funcArr.push(func)
}
emitter.on('form-item-created', callback)
onUnmounted(() => {
    emitter.off('form-item-created', callback)
    funcArr = []
})
</script>